package com.meihua.baoleyi.ui;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.meihua.baoleyi.R;
import com.meihua.baoleyi.base.BaseActivity;
import com.meihua.baoleyi.common.MyApp;
import com.meihua.baoleyi.dialog.ReleasePhotoDialog;
import com.meihua.baoleyi.utils.FileUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by liming on 2017/10/17.
 * 我的认证
 */

public class MyCertificationActivity extends BaseActivity {

    @Bind(R.id.text_back)
    ImageView textBack;
    @Bind(R.id.etx_check_id_real_name)
    EditText etxRealName;
    @Bind(R.id.etx_check_id_card_num)
    EditText etxCardNum;
    @Bind(R.id.iv_check_id_positive_picture)
    ImageView ivPositivePicture;
    @Bind(R.id.iv_positive_upload)
    ImageView ivPositiveUpload;
    @Bind(R.id.iv_check_id_back_picture)
    ImageView ivBackPicture;
    @Bind(R.id.iv_back_upload)
    ImageView ivBackUpload;
    @Bind(R.id.tv_next)
    TextView tvNext;
    @Bind(R.id.text_title)
    TextView textView;

    private static final int REQUEST_POSITIVE_CAMERA_CODE = 101;
    private static final int REQUEST_POSITIVE_PHOTO_CODE = 102;
    private static final int REQUEST_BACK_CAMERA_CODE = 103;
    private static final int REQUEST_BACK_PHOTO_CODE = 104;
    private String mPositivePath = null;
    private String mBackPath = null;
    private List<String> imgList = new ArrayList<>();
    private String userName; //真实姓名
    private String userIdcard; //身份证号码

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_certification);
        ButterKnife.bind(this);
        initView();
    }

    /**
     * 加载视图
     */
    private void initView() {
        textView.setText("身份认证");
        etxRealName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                checkEnable();
            }
        });
        //输入框监听
        etxCardNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                checkEnable();
            }
        });
    }

    @OnClick({R.id.text_back, R.id.iv_positive_upload, R.id.iv_back_upload, R.id.tv_next})
    public void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.text_back://返回
                finish();
                break;
            case R.id.iv_positive_upload://正面照
                goImageGridActivity(REQUEST_POSITIVE_CAMERA_CODE, REQUEST_POSITIVE_PHOTO_CODE);
                break;
            case R.id.iv_back_upload://背面照
                goImageGridActivity(REQUEST_BACK_CAMERA_CODE, REQUEST_BACK_PHOTO_CODE);
                break;
            case R.id.tv_next:
                goNextActivity();
                break;
        }
    }

    /**
     * 选择图片
     *
     * @param cameraCode
     * @param photoCode
     */
    private void goImageGridActivity(int cameraCode, int photoCode) {
        ReleasePhotoDialog dialog = new ReleasePhotoDialog(MyCertificationActivity.this, cameraCode, photoCode);
        dialog.show();
    }

    /**
     * 下一步
     */
    private void goNextActivity() {
        if (etxRealName.getText() == null || TextUtils.isEmpty(etxRealName.getText()) || TextUtils.isEmpty(etxRealName.getText().toString().trim())) {
            Toast.makeText(this, "请输入您的真实姓名", Toast.LENGTH_SHORT).show();
            return;
        }
        if (etxCardNum.getText() == null || TextUtils.isEmpty(etxCardNum.getText()) || TextUtils.isEmpty(etxCardNum.getText().toString().trim())) {
            Toast.makeText(this, "请输入您的身份证号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mPositivePath == null) {
            Toast.makeText(this, "请选择身份证正面图片", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mBackPath == null) {
            Toast.makeText(this, "请选择身份证反面图片", Toast.LENGTH_SHORT).show();
            return;
        }
        Pattern pattern = Pattern.compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$");
        Matcher matcher = pattern.matcher(etxCardNum.getText().toString().trim());
        if (!matcher.matches()) {
            Toast.makeText(this, "您输入的身份证号格式不正确", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(MyCertificationActivity.this, CheckIdSubmitActivity.class);
        userName = etxRealName.getText().toString().trim();
        userIdcard = etxCardNum.getText().toString().trim();
        intent.putExtra("user_name", userName);
        intent.putExtra("user_idcard", userIdcard);
        intent.putExtra("img_reverse", mBackPath); //背面
        intent.putExtra("img_front", mPositivePath); //正面
        startActivityForResult(intent, 105);
    }

    /**
     * 选择图片的回调
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //相册选择 正面照
        if (requestCode == REQUEST_POSITIVE_PHOTO_CODE) {
            if (data == null || data.getData() == null) {
                return;
            }
            mPositivePath = getPhotoPath(data);
            checkEnable();
            //设置正面照片
            Glide.with(this).load(mPositivePath).into(ivPositiveUpload);
            return;
        }
        //相册选择 背面照
        if (requestCode == REQUEST_BACK_PHOTO_CODE) {
            if (data == null || data.getData() == null) {
                return;
            }
            mBackPath = getPhotoPath(data);
            checkEnable();
            //设置背面照片
            Glide.with(this).load(mBackPath).into(ivBackUpload);
            return;
        }
        //拍照选择 正面照
        if (requestCode == REQUEST_POSITIVE_CAMERA_CODE) {
            mPositivePath = FileUtil.getUtil().SDPATH + "photo_release" + MyApp.getInstance().time + ".png";
            checkEnable();
            Glide.with(this).load(mPositivePath).into(ivPositiveUpload);
//            upImage(mPositivePath);
            return;
        }
        //拍照选择 背面照
        if (requestCode == REQUEST_BACK_CAMERA_CODE) {
            mBackPath = FileUtil.getUtil().SDPATH + "photo_release" + MyApp.getInstance().time + ".png";
            checkEnable();
            Glide.with(this).load(mBackPath).into(ivBackUpload);
            return;
        }
        if (requestCode == 105 && resultCode == RESULT_OK) {
            finish();
        }
    }

    /**
     * 设置点击状态
     */
    private void checkEnable() {
        if (!TextUtils.isEmpty(etxRealName.getText()) && !TextUtils.isEmpty(etxCardNum.getText()) && etxCardNum.getText().length() > 17 && !TextUtils.isEmpty(mPositivePath) && !TextUtils.isEmpty(mBackPath)) {
            tvNext.setEnabled(true);
        } else {
            tvNext.setEnabled(false);
        }
    }

    /**
     * 获取相册图片回调的路径
     * @param data
     * @return
     */
    private String getPhotoPath(Intent data) {
        String[] pojo = {MediaStore.MediaColumns.DATA};
        Cursor cursor = getContentResolver().query(data.getData(), pojo, null, null, null);
        int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
        cursor.moveToFirst();
        return cursor.getString(columnIndex);
    }
}


